package vikaa.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import vikaa.adapter.WowoCreate3Adapter;
import vikaa.bean.WeiboFriend;
import vikaa.timelinepackage.Timeline;
import vikaa.timelinepackage.TimelineSettings;
import vikaa.tools.HttpUtil;
import vikaa.tools.ValueClass;
import vikaa.wowo.R;
import vikaa.wowo.cache.InvitorSqlStoragePrivate;
import vikaa.wowo.cache.UserInfoSharePreference;

public class WowoCreate3 extends Activity implements OnItemClickListener{
	private ProgressDialog pd;
	private TextView titleTv;
	private LinearLayout backBtn;
	private ImageView submitBtn;
	private CheckBox inviteCB;
	private RelativeLayout sinaBtn;
	private RelativeLayout phoneBtn;
	private LinearLayout invitorLl;
	private ListView fd_listview;
	private WowoCreate3Adapter mAdapter;
	private ArrayList<WeiboFriend> wbfList = new ArrayList<WeiboFriend>() ;
	public static ArrayList<WeiboFriend> mList = new ArrayList<WeiboFriend>();
	private String state;
	private String spacename;
	public static boolean isfinish = false;
	
	public static boolean issetting = false;
	//private final static int hostNum = (Integer.valueOf(Timeline.managerCount));
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wowo_create3);
		initview();
		isfinish=false;
		if(issetting){
			initManagerMember();
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isfinish){
			WowoCreate2.isfinish=true;
			WowoCreate1.isfinish=true;
			InvitorSqlStoragePrivate.refreshWeibofd(WowoCreate3.this);
			InvitorSqlStoragePrivate.refreshContactfd(WowoCreate3.this);
			InvitorSqlStoragePrivate.dropchoosed(WowoCreate3.this);
			finish();
		}
		mList.clear();
		wbfList.clear();
		mAdapter.notifyDataSetChanged();
		try{		
			wbfList = InvitorSqlStoragePrivate.getChoosedinSql(getApplicationContext());
			if(wbfList.size() > 0){
				fd_listview.setVisibility(View.VISIBLE);
				Message msg = mhandler.obtainMessage(1);
				msg.obj = wbfList;
				msg.sendToTarget();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		InvitorSqlStoragePrivate.refreshWeibofd(WowoCreate3.this);
		InvitorSqlStoragePrivate.refreshContactfd(WowoCreate3.this);
		InvitorSqlStoragePrivate.dropchoosed(WowoCreate3.this);
		
	}

	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what){
			case 1:
				if(msg.obj != null){
					ArrayList<WeiboFriend> strings = (ArrayList<WeiboFriend>) msg.obj;
					if(!strings.isEmpty()){
						inviteCB.setChecked(true);
						invitorLl.setVisibility(View.VISIBLE);
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
					}
				}
				break;
			case 2:
				pd.dismiss();
				WowoCreate1.isfinish=true;
				Mywowo.isrefresh = true;
				Intent intent = new  Intent(WowoCreate3.this,Timeline.class);
				intent.putExtra("sid", (String)msg.obj);
				intent.putExtra("role", String.valueOf(ValueClass.ROLE_CREATOR));
				intent.putExtra("count", "0");
				intent.putExtra("spacename", spacename);
				intent.putExtra("cover", "");
				intent.putExtra("credits", "0");
				intent.putExtra("member", "0");
				intent.putExtra("host", "1");
				intent.putExtra("state", state);
				startActivity(intent);
				Toast.makeText(getApplicationContext(), "创建窝窝成功", Toast.LENGTH_SHORT).show();
				finish();
				break;
			case 3:
				pd.dismiss();
				if(msg.obj != null){
					Toast.makeText(WowoCreate3.this, String.valueOf(msg.obj), 500).show();
				}
				break;
			}
		}
	};
	public void initview(){
		Intent i = getIntent();
		state = i.getExtras().getString("state");
		spacename = i.getExtras().getString("name");
		titleTv = (TextView)findViewById(R.id.titleTv);
		titleTv.setText(spacename);
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setImageResource(R.drawable.wowo_login_submit_default);
		submitBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!issetting){
					if(inviteCB.isChecked()){
						switch(mList.size()){
						case 0:
							new AlertDialog.Builder(WowoCreate3.this).setTitle(getString(R.string.tip)).setMessage(getString(R.string.invite_msg1))
							.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									
								}
							}).show();
							break;
							default:
								Intent i = new Intent(WowoCreate3.this,WowoCreate4.class);
								i.putExtra("name", titleTv.getText().toString());
								i.putExtra("state", state);
								WowoCreate4.inviteflag = false;
								startActivity(i);
								break;
						}
					}
					else{
						new AlertDialog.Builder(WowoCreate3.this).setTitle(getString(R.string.tip)).setMessage(getString(R.string.invite_msg2))
						.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								pd.show();
								new WowoCreateThread().start();
							}
						}).setNegativeButton(getString(R.string.back), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								
							}
						}).show();
					}
				}
				else{
					switch(mList.size()){
					case 0:
						finish();
						break;
						default:
							Intent i = new Intent(WowoCreate3.this,WowoCreate4.class);
							i.putExtra("name", titleTv.getText().toString());
							i.putExtra("state", state);
							WowoCreate4.inviteflag = true;
							startActivity(i);
							break;
					}
				}
			}
		});
		inviteCB = (CheckBox)findViewById(R.id.inviteCB);
		//inviteCB.setChecked(InviteButtonSharePreference.getState(getApplicationContext()));
		if(!inviteCB.isChecked())submitBtn.setImageResource(R.drawable.wowo_login_submit_default);
		inviteCB.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(!inviteCB.isChecked()){
					new AlertDialog.Builder(WowoCreate3.this).setTitle(getString(R.string.tip)).setMessage(getString(R.string.invite_msg3))
					.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							inviteCB.setChecked(false);
							//InviteButtonSharePreference.putState(getApplicationContext(), inviteCB.isChecked());
							submitBtn.setImageResource(R.drawable.wowo_login_submit_default);
							invitorLl.setVisibility(View.INVISIBLE);
						}
					}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							inviteCB.setChecked(true);
						}
					}).show();
				}
				else{
					if(mList.size()>0){
						invitorLl.setVisibility(View.VISIBLE);
					}
					submitBtn.setImageResource(R.drawable.wowo_create_invite_default);
				}
			}
		});
		sinaBtn = (RelativeLayout)findViewById(R.id.sinaBtn);
		sinaBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				WeiboFriendChoose.inviteflag = false;
				WeiboFriendChoose.callflag = false;
				WeiboFriendChoose.setflag = false;
				startActivity(new Intent(WowoCreate3.this,WeiboFriendChoose.class));
			}	
		});
		phoneBtn = (RelativeLayout)findViewById(R.id.phoneBtn);
		phoneBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(WowoCreate3.this,ContactFriendChoose.class));
			}	
		});
		fd_listview = (ListView) findViewById(R.id.invitorListview);
		mAdapter = new WowoCreate3Adapter(WowoCreate3.this, mList, fd_listview);
		fd_listview.setAdapter(mAdapter);
		fd_listview.setOnItemClickListener(this);
		invitorLl = (LinearLayout)findViewById(R.id.invitorLl);
		invitorLl.setVisibility(View.INVISIBLE);
		
		pd = new ProgressDialog(WowoCreate3.this);
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setMessage(getString(R.string.create_wowo));
	}
	
	private void initManagerMember(){
		new Thread(new Runnable() {
			public void run() {
				Map<String,String> map = new HashMap<String, String>();
				map.put("space_id", TimelineSettings.space_id);
				map.put("page", "1");
				try {
					wbfList.clear();
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL + "space/managers", map));
					Log.i("d", jsonObj.toString());
					if(jsonObj.getString("result").equals("1")){
						JSONArray info = jsonObj.getJSONArray("info");
						for(int i=0;i<info.length();i++){
							WeiboFriend wf = new WeiboFriend();
							wf.setId(info.getJSONObject(i).getString("uid"));
							wf.setName(info.getJSONObject(i).getString("screen_name"));
							wf.setPhone("0");
							wf.setSelected(true);
							InvitorSqlStoragePrivate.saveChoosedinSql(wf, getApplicationContext());
						}	
						wbfList.clear();
						wbfList = InvitorSqlStoragePrivate.getChoosedinSql(getApplicationContext());
						if(wbfList.size() > 0){
							fd_listview.setVisibility(View.VISIBLE);
							Message msg = mhandler.obtainMessage(1);
							msg.obj = wbfList;
							msg.sendToTarget();
						}
					}
				}catch (JSONException e) {
					
				}
			}
		}).start();
	}
	
	class WowoCreateThread extends Thread{
    	boolean isrun = true;
    	@Override
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("spacename", titleTv.getText().toString());
    			map.put("state", state);
    			String url = HttpUtil.BASE_URL + "space/create";
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
					String result = jsonObj.getString("result");
					if(result.equals("1")){
						String space_id = jsonObj.getJSONObject("info").getString("space_id");
						Message msg = mhandler.obtainMessage(2);
						msg.obj = space_id;
						mhandler.sendMessage(msg);
					}else if(result.equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getJSONObject("info").getJSONArray("space").toString();
						mhandler.sendMessage(msg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
		if(!mList.get(arg2).getId().equals(UserInfoSharePreference.getUid(WowoCreate3.this))){
			new AlertDialog.Builder(WowoCreate3.this).setTitle(getString(R.string.tip)).setMessage( "不邀请" + mList.get(arg2).getName() +"吗？")
			.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					InvitorSqlStoragePrivate.delectChoosedinSql(mList.get(arg2), WowoCreate3.this);
					if(mList.get(arg2).getPhone().length() > 4){
						InvitorSqlStoragePrivate.updateContactfdSql(mList.get(arg2).getPhone(), false, WowoCreate3.this);
					}else{
						InvitorSqlStoragePrivate.updateWeibofdSql(mList.get(arg2).getId(), false, WowoCreate3.this);
					}
					mList.remove(arg2);
					mAdapter.notifyDataSetChanged();
					if(mList.size() == 0){
						fd_listview.setVisibility(View.INVISIBLE);
						invitorLl.setVisibility(View.INVISIBLE);
					}
				}
			}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			}).show();
		}
	}
}
